package com.jy.wms.common.base;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

public class KuaiDiGuiJi {

    public String zhongTong(){
        //发送请求
        try {
            String company_id = "179588becad34c4e8257cbc02f7e36ed";
            String msg_type = "NEW_TRACES";
            String key = "BC797736605E20EBE1244659E5021FEE";
            String data = "[";
            data += "\"486556812786\"";
            data += "]";
            String body = "company_id=" + company_id + "&msg_type=" + msg_type + "&data="+data;
            String sign = DigestUtil.digest(body,key,"GBK");
            System.out.println("body= " + body);
            System.out.println("sign= " + sign);
            System.out.println("data= " + data);


            String myUrl = "http://japi.zto.cn/traceInterfaceNewTraces";
            System.out.println("url= " + myUrl);
            //发送POST请求
            URL url = new URL(myUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("x-companyId", company_id);
            conn.setRequestProperty("x-dataDigest", sign);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);

            conn.setRequestProperty("Content-Length", "" + body.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(body);
            out.flush();
            out.close();

            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

    public String baiShi(){
        //发送请求
        try {
            String partnerID = "59";
            String partnerKey = "XTS0BVRG";
            String messageType = "XML";
            String serviceType = "KD_TRACE_QUERY";

            List<String> mailNo = new ArrayList<>();
            mailNo.add("70959317899002");
            JSONObject json = new JSONObject();
            JSONObject mail = new JSONObject();
            mail.put("mailNo",JSONArray.fromObject(mailNo));
            json.put("mailNos",mail);

            StringBuilder sb = new StringBuilder();
            sb.append("<request>");
            sb.append("     <mailNos>");
            sb.append("         <mailNo>50004090806944</mailNo>");
            sb.append("     </mailNos>");
            sb.append("</request>");


            System.out.println("mailNos=" + json.toString());

            String sign = getMD5(sb.toString() + partnerKey);

            String body = "&sign="+ sign +"&partnerID=" + partnerID + "&serviceType="+serviceType + "&bizData="+
                    sb.toString();
            System.out.println("sign= " + sign);
            System.out.println("body= " + body);


            String myUrl = "http://openapi.800best.com/api-server/kd/api/process";
            System.out.println("url= " + myUrl);
            //发送POST请求
            URL url = new URL(myUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);

            conn.setRequestProperty("Content-Length", "" + body.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(body);
            out.flush();
            out.close();

            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

    /**
     * 对字符串md5加密(小写+字母)
     *
     * @param str 传入要加密的字符串
     * @return  MD5加密后的字符串
     */
    public static String getMD5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        System.out.println("百世返回信息：");
        System.out.println(new KuaiDiGuiJi().baiShi());
//        System.out.println("中通返回信息：");
//        System.out.println(new KuaiDiGuiJi().zhongTong());

    }




}
